package cn.edu.cqut.base.activity;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import cn.edu.cqut.base.myview.BaseProgressDialog;

/**
 * 
 * @author chenliang
 * @version v1.1
 * @date 2014-2-23
 * 
 */
public abstract class BaseActivity extends Activity implements OnClickListener,
		OnItemClickListener {
	// 按两次退出程序
	private int backCount = 0;
	// 默认为0 0代表不会退出 1代表按两次退出 2代表弹出提示框
	private int backMode = 0;
	protected static final int BACK_MODE_2COUNT = 1;
	protected static final int BACK_MODE_DIALOG = 2;

	private BaseProgressDialog progressDialog = null;

	protected Handler baseHandler;

	protected Context mContext;

	protected Map<String, Object> params = new HashMap<String, Object>();

	protected View loadView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
						| WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		mContext = this;
		baseHandler = new Handler();
		progressDialog = new BaseProgressDialog(this);
		progressDialog.setCanceledOnTouchOutside(false);
	}

	/**
	 * 设置title内容
	 */
	public void setTitleMessage(String message) {
		// 引用base_title布局文件里面的TextView
		TextView title = ((TextView) findViewById(R.id.title).findViewById(
				R.id.tvTitle));
		title.setText(message);
		// 文字过多时把字体设置小
		if (message.length() >= 20) {
			title.setTextSize(10.0f);
		} else if (message.length() >= 15) {
			title.setTextSize(12.0f);
		} else if (message.length() >= 10) {
			title.setTextSize(14.0f);
		}
	}

	/** 设置标题栏右边按钮 */
	protected void setTitleButton(int imageId, OnClickListener listener) {
		TextView button = (TextView) findViewById(R.id.title).findViewById(
				R.id.btnTitleRight);
		button.setOnClickListener(listener);
		button.setVisibility(View.VISIBLE);
		button.setCompoundDrawablesWithIntrinsicBounds(getResources()
				.getDrawable(imageId), null, null, null);
	}

	// 显示正在加载界面
	protected void showLoadView() {
		if (loadView == null) {
			loadView = findViewById(R.id.lLoading);
		}
		loadView.setVisibility(View.VISIBLE);
		ImageView imageView = (ImageView) loadView
				.findViewById(R.id.loadingImg);
		AnimationDrawable animationDrawable = (AnimationDrawable) imageView
				.getDrawable();
		animationDrawable.start();
	}

	// 隐藏加载界面
	protected void hideLoadView() {
		if (loadView != null) {
			loadView.setVisibility(View.GONE);
		}
	}

	// 设置返回按钮可见
	protected void setBackButton() {
		View view = findViewById(R.id.title).findViewById(R.id.btnReturn);
		view.setVisibility(View.VISIBLE);
		view.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	/**
	 * 设置进度对话框消息
	 * 
	 * @param message
	 */
	public void setProgressDialogMessage(String message) {
		progressDialog.setMessageText(message);
	}

	/**
	 * 显示进度对话框
	 */
	public void showProgressDialog() {
		progressDialog.show();
		progressDialog.startAnim();
	}

	/**
	 * 显示进度对话框,带有消息
	 */
	public void showProgressDialog(String message) {
		setProgressDialogMessage(message);
		progressDialog.show();
		progressDialog.startAnim();
	}

	/**
	 * 关闭进度对话框
	 */
	public void closeProgressDialog() {
		if (progressDialog.isShowing()) {
			progressDialog.dismiss();
		}
	}

	/**
	 * 显示短提示的消息
	 * 
	 * @param message
	 */
	public void showShortToast(String message) {
		Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT)
				.show();
	}

	/**
	 * 显示长提示的消息
	 * 
	 * @param message
	 */
	public void showLongToast(String message) {
		Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG)
				.show();
	}

	@Override
	public void onClick(View v) {
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
	}

	/**
	 * 向服务器发送数据时调用的方法
	 * 
	 * @param callBack
	 *            传入数据处理的回调接口
	 */
	public void send(BaseThreadCallBack callBack) {
		new BaseThread(callBack).start();
	}

	/**
	 * 向服务器发送数据时调用的方法
	 * 
	 * @param callBack
	 *            传入数据处理的回调接口,该接口没有empty和error方法
	 */
	public void send(BaseCallBack callBack) {
		new BaseThread2(callBack).start();
	}

	/**
	 * 向服务器发送数据时调用的方法
	 * 
	 * @param callBack
	 *            传入数据处理的回调接口,进度框显示的消息，该接口没有empty和error方法
	 */
	public void send(String message, BaseCallBack callBack) {
		new BaseThread2(callBack, message).start();
	}

	/**
	 * 处理线程回调接口
	 */
	public interface BaseThreadCallBack {
		/** 线程开始执行时回调方法 */
		public void handleEmpty();

		/** 发送数据到服务器调用方法,返回服务器回传数据 */
		public String sendData() throws Exception;

		/** 提交数据成功时回调方法,传入服务器返回的数据 */
		public void handleSuccess(String result) throws Exception;

		/** 提交数据失败时回调方法，传入错误的消息 */
		public void handleError(String errorMessage);
	}

	/**
	 * 处理线程回调接口
	 */
	public interface BaseCallBack {

		/** 发送数据到服务器调用方法,返回服务器回传数据 */
		public String sendData() throws Exception;

		/** 提交数据成功时回调方法,传入服务器返回的数据 */
		public void handleSuccess(String result) throws Exception;
	}

	/**
	 * 公共的线程调用
	 */
	class BaseThread extends Thread {
		private BaseThreadCallBack callBack = null;
		private String result = null;

		public BaseThread(BaseThreadCallBack callBack) {
			this.callBack = callBack;
		}

		@Override
		public void run() {
			// 处理提交前的处理
			baseHandler.post(new Runnable() {
				@Override
				public void run() {
					callBack.handleEmpty();
				}
			});
			try {
				// 在这里提交数据
				result = callBack.sendData();
			} catch (Exception e) {
				// 处理错误
				baseHandler.post(new Runnable() {
					@Override
					public void run() {
						callBack.handleError(result.toString());
					}
				});
			}
			// 处理正确的结果
			if (result != null) {
				baseHandler.post(new Runnable() {
					@Override
					public void run() {
						try {
							callBack.handleSuccess(result.toString());
						} catch (Exception e) {
							e.printStackTrace();
							showLongToast("解析数据失败!数据：" + result.toString());
						}
					}
				});
			}

		}
	}

	/**
	 * 公共的线程调用
	 */
	class BaseThread2 extends Thread {
		private BaseCallBack callBack = null;
		private String result = null;
		private String message = "正在加载数据...";

		public BaseThread2(BaseCallBack callBack) {
			this.callBack = callBack;
		}

		public BaseThread2(BaseCallBack callBack, String message) {
			this.callBack = callBack;
			this.message = message;
		}

		@Override
		public void run() {
			// 处理提交前的处理
			baseHandler.post(new Runnable() {
				@Override
				public void run() {
					showProgressDialog(message);
				}
			});
			try {
				// 在这里提交数据
				result = callBack.sendData();
			} catch (Exception e) {
				// 处理错误
				baseHandler.post(new Runnable() {
					@Override
					public void run() {
						closeProgressDialog();
						if (result != null)
							showLongToast(result.toString());
					}
				});
			}
			// 处理正确的结果
			if (result != null) {
				baseHandler.post(new Runnable() {
					@Override
					public void run() {
						try {
							closeProgressDialog();
							callBack.handleSuccess(result.toString());
						} catch (Exception e) {
							e.printStackTrace();
							showLongToast("解析数据失败!数据：" + result.toString());
						}
					}
				});
			}

		}
	}

	/** 界面跳转相关方法 */
	public void startIntent(Class clazz) {
		startIntent(clazz, null);
	}

	public void startIntent(Class clazz, Map<String, Object> params) {

		startActivity(getIntent(clazz, params));
	}

	private Intent getIntent(Class clazz, Map<String, Object> params) {
		Intent intent = new Intent(this, clazz);
		if (params != null) {
			for (Entry<String, Object> entry : params.entrySet()) {
				Object value = entry.getValue();
				if (value instanceof Boolean) {
					intent.putExtra(entry.getKey(),
							Boolean.parseBoolean(entry.getValue().toString()));
				} else if (value instanceof Float) {
					intent.putExtra(entry.getKey(),
							Float.parseFloat(entry.getValue().toString()));
				} else if (value instanceof Double) {
					intent.putExtra(entry.getKey(),
							Double.parseDouble(entry.getValue().toString()));
				} else if (value instanceof Integer) {
					intent.putExtra(entry.getKey(),
							Integer.parseInt(entry.getValue().toString()));
				} else if (value instanceof Long) {
					intent.putExtra(entry.getKey(),
							Long.parseLong(entry.getValue().toString()));
				} else {
					intent.putExtra(entry.getKey(), entry.getValue().toString());
				}
			}
		}
		return intent;
	}

	public void startIntentForResult(Class clazz, int requestCode) {
		startActivityForResult(getIntent(clazz, null), requestCode);
	}

	public void startIntentForResult(Class clazz, Map<String, Object> params,
			int requestCode) {
		startActivityForResult(getIntent(clazz, params), requestCode);
	}

	/**
	 * 设置退出模式
	 * 
	 * @param mode
	 *            BACK_MODE_2COUNT--按两次退出 BACK_MODE_DIALOG--弹出提示框退出
	 */
	public void setBackMode(int mode) {
		backMode = mode;
	}

	// 监听返回键
	public boolean dispatchKeyEvent(KeyEvent event) {
		if (event.getAction() == KeyEvent.ACTION_DOWN
				&& event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			if (backMode == BACK_MODE_2COUNT) {
				exitByCount();
			} else if (backMode == BACK_MODE_DIALOG) {
				exitByDialog();
			}
			// 默认
			else if (backMode == 0) {
				return super.dispatchKeyEvent(event);
			}
			return false;
		}

		return super.dispatchKeyEvent(event);
	};

	// 通过连续按两次退出程序
	public void exitByCount() {
		backCount++;
		if (backCount >= 2) {
			finish();
			System.exit(0);
		} else {
			Toast.makeText(getApplicationContext(), "再按一次回到桌面",
					Toast.LENGTH_SHORT).show();
			new Thread() {
				public void run() {
					try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					backCount = 0;
				};
			}.start();
		}
	}

	// 通过弹出返回对话框退出程序
	public void exitByDialog() {
		AlertDialog.Builder builder = new Builder(BaseActivity.this);
		builder.setMessage("确定要退出程序");
		builder.setIcon(android.R.drawable.ic_dialog_alert);
		builder.setTitle("提示");
		builder.setPositiveButton("确定",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						finish();
						System.exit(0);
					}
				});
		builder.setNegativeButton("取消",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		builder.create().show();
	}

	/** 重载父类的setContentView方法，目的是自动初始化组件 */
	@Override
	public void setContentView(int layoutResID) {
		super.setContentView(layoutResID);
		initComponent();
	}

	/**
	 * 通过反射初始化控件，要求控件的名字和布局文件名字一致,不一致通过ID注解进行配置
	 * */
	protected void initComponent() {
		Class clazz = this.getClass();
		Field[] fields = clazz.getDeclaredFields();
		for (Field field : fields) {
			field.setAccessible(true);
			Class type = field.getType();
			if (View.class.isAssignableFrom(type)) {
				String idName = field.getName();
				// 如果字段上有注解则采用注解的id
				ID idAnnotation = field.getAnnotation(ID.class);
				if (idAnnotation != null) {
					idName = idAnnotation.value();
				}

				View view = findViewById(getResources().getIdentifier(idName,
						"id", getPackageName()));

				if (view != null) {
					if ("Button".equals(view.getClass().getSimpleName())) {
						view.setOnClickListener(this);
					}
					try {
						field.set(this, view);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	// 这里必须添加@Retention(RetentionPolicy.RUNTIME)，不然程序运行过程中获取不到注解
	@Retention(RetentionPolicy.RUNTIME)
	@Target(ElementType.FIELD)
	// 只能将注解加到方法上
	/**控件上的ID注解*/
	public @interface ID {
		String value();
	}

	/***
	 * 验证EditText是否为空
	 * 
	 * @param edts
	 *            校验的EditText
	 * @param messages
	 *            提示信息!
	 * @return 成功归还ture 失败归还 false
	 */
	protected boolean validationEditText(EditText[] edts, String[] messages) {
		int i = 0;
		for (EditText editText : edts) {
			if (editText == null) {
				return false;
			}
			if (TextUtils.isEmpty(editText.getText().toString().trim())) {
				showLongToast(messages[i]);
				editText.requestFocus();
				return false;
			}
			i++;
		}
		return true;
	}
}
